#!/usr/bin/env python2
#-*- coding: utf-8 -*-
import  time
import os
import json
import uuid
import datetime
import web
from Umpweb.base import render_jinja
from Umpweb.db import api as db_api
from Umpweb.common import utils
from Umpweb.common import log
from Umpweb.webapps import base 
from Ump.defs import  UMP_LICENSE_CMD_DIR, UMP_LICENSE_DIR, \
    DOWNLOAD_TAR_DIR, LICH_HOST_IP_FILE, DECOMMPRESS_DIR

urls = (
    '/create/message'  ,    'ApplyMessage',
    '/create/upload'    ,   'ApplyUpload',
    '/create/success'  ,    'ApplySuccess',
    '/create/home' ,        'LicenseHome',
    '/list',                'LicenseList',
    '/download',            'Download',
    '/upload',              'LicenseSubmit',
    '/grid',                'GridLicense',

)

LOG = log.get_log('Umpweb.webapps.license')
app = web.application(urls, locals())
render = render_jinja('static/templates/license', encoding='utf-8',)


class  ApplyMessage:

    def __init__(self):
        pass

    def GET(self):

        return render.message()

    def POST(self):
        values = dict(**web.input())
        web.header("Content-Type", "application/json")
        body = {"LicenseCreate": {'params': values}}

        return utils.web_return(body)

class ApplyUpload:

    def __init__(self):
        pass

    def GET(self):
        return render.upload()
    def POST(self):
        web_input = web.input()
        values = dict(**web.input())
        web.header("Content-Type", "application/json")
        body = {"LicenseCreate": {'params': values}}
        return utils.web_return(body)

class ApplySuccess:

    def __init__(self):
        pass
    def GET(self):
        return  render.success()
    
class  LicenseHome(base.ClusterLicenseBase):

    def GET(self):
        cluster = self.cluster_license() 
        return render.licensehome(cluster=cluster)


STATUS_MAP = { 
    'done': '成功',
    'failed': '失败',
}


def verify_ip(ip_str):
    try:
        return True if len([x for x in ip_str.split('.') if int(x)<256]) == 4 else False
    except:
        return False
    
    
class HelpBase(object):

    def __init__(self):
        self.abs_path = os.path.dirname(os.path.realpath(__file__))
        self.user = web.ctx.session.user
        self.step_prefix = 'license_step.'
        
        
class About:
    def GET(self):
        return render.about()

# class About_vstor:
#     def GET(self):
#         version_file = "/opt/fusionstack/etc/ump/git-info"
#         ump_version,err = local_exec("cat %s|grep Version |awk '{print $2}'"%(version_file))
#         lich_version = ''
#         hosts = db_api.host_get_all()
#         for host in hosts:
#             if host.version :
#                 lich_version = host.version
#                 continue
                
        return render.about_vstor(ump_version=ump_version,lich_version=lich_version)
#
# class UpLoadfile:
#     get_file = web.input(myfile={})


class Register(HelpBase):


    def GET(self):
        cluster_objs = db_api.cluster_get_all()
        source = self.permanager.get_module_by_type('license')
        isread = 'false'
        msg = ''
        pname = ''
        if not cluster_objs:
            return render.register(isread=isread,msg=msg,pname=pname)
        cluster_list = [[i.id, i.name] for i in cluster_objs]
        cluster_json = json.dumps(cluster_list)
        web.header("Content-Type", "application/json")  
        all_license_permit ,all_license_total = 0,0
        for cluster in cluster_objs:
            clusterhosts = db_api.host_get_with_cluster(cluster.id)
            clustername = cluster.name
            frees = [h.node_register_info for h in clusterhosts if h.node_register_info == 'free']

            license_permit = cluster.license_permit
            if license_permit:
                try:
                    license_permit = int(license_permit)
                except:
                    license_permit = 0
                all_license_permit += license_permit

            is_overdate_day = False
            node_stat_list = [x.node_stat_at for x in clusterhosts if x.node_stat_at is not None]
            if [x for x in node_stat_list if x == 0 ] and cluster.license_stat != 'permanent':
                is_overdate_day = True

            now = datetime.datetime.now()
            delta = datetime.timedelta(seconds=1)
            if is_overdate_day and cluster.invalid_date and now - cluster.invalid_date > delta:
                clustername = ''

            if frees and clustername:
                pname += clustername + ','
        pname = pname.strip(',')

        all_license_permit = (all_license_permit / 1024) + 1 if all_license_permit else all_license_permit
        all_license_permit = "%sT"%all_license_permit 
        licensefile = os.listdir('%s/ump/manage/license'%(home))

        return render.register(cluster=cluster_json, default_id=cluster_list[0][0],pname=pname,all_license_permit=all_license_permit,\
                               default_name=cluster_list[0][1],isread=isread,msg=msg,licensefile=licensefile)



class MakeInfo:

    def GET(self):
        return render.makeinfo()


class Success_license(HelpBase):
    def GET(self):
        return render.registered()

class Registered(HelpBase):
    def GET(self, dir_path):
        web.header("Content-Type", "text/plain")
        pass

class LicenseList(HelpBase):
    def GET(self):
        web.header("Content-Type", "text/plain")
        step_dirs = os.listdir(self.abs_path)
        step_number = 0
        for i in range(1,4):
            step_file = "%s%s" % (self.step_prefix, i)
            if step_file in step_dirs:
                step_number = i
        LOG.info('%s' % step_number)
        return render.license_list(step_number=step_number)
    
class Download(HelpBase):
    def GET(self):
        webinput = web.input()
        temp_dir = os.path.join(self.abs_path, str(uuid.uuid1()))
        os.makedirs(temp_dir)
        step_number = os.path.join(self.abs_path, '%s2' % self.step_prefix)
        os.system("touch %s" % (step_number))

        body = {'LicenseSniffer':{'params':{}}}
        reply = web.config._server.api_sync_call(body)
        reply = json.loads(reply)
        if reply.get('reply', {}).get('is_success'):
            records = reply.get('records', {})
            stdout = records.get('stdout')
            nodesniffer = records.get('nodesniffer', {})
        else:
            raise Exception(reply.get('reply').get('error'))

        node_info_file = "nodes.info"
        node_info_path = os.path.join(temp_dir, node_info_file)
        utils._exec_pipe('truncate --size 0 > %s' % (node_info_path))
        for (key, val) in  nodesniffer.items():
            utils._exec_pipe('echo "%s" >> %s' % (val.strip(), node_info_path))

        utils._exec_pipe('echo "%s" > %s/cluster.info' % (stdout.strip(), temp_dir))
        tar_cmd = 'tar -C %s -cf %s/cluster.tar ./' % (temp_dir, temp_dir)
        os.system(tar_cmd)
        register_file = os.path.join(temp_dir, 'cluster.tar')
        f = None
        username = web.ctx.session.user
        try:
            f = open(register_file, "rb")
            web.header('Content-Type','application/octet-stream')
            web.header('Content-disposition', 'attachment; filename=cluster.tar')
            while True:
                c = f.read()
                if c:
                    yield c
                else:
                    break
        except Exception, e:
            LOG.info('%s' % (e))
            event_values = {
                    'user_id': web.config._session.user.id,
                    'operation': u'生成注册信息失败',
                    'resource': "注册",
                    'oplog_obj': u"注册",
                    'status':STATUS_MAP.get('failed'),
                    'detail':u'%s' % e
            }
            db_api.oplog_create(event_values)
            yield 'Error'
        finally:
            if f:
                f.close()
            os.system('rm -rf %s'%(temp_dir))


class LicenseSubmit(HelpBase):

    def __init__(self):
        self.strtime = time.strftime('%Y-%m-%d.%H:%M:%S', time.localtime())

    def POST(self):
        webfiles = web.webapi.rawinput().get('license_file')
        filepath = webfiles.filename.replace('\\', '/')  # replaces the windows-style slashes with linux ones.
        filename = filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
        uploadfile = "%s/%s" % (DOWNLOAD_TAR_DIR, filename)
        if os.path.exists(uploadfile):
            rm_cmd = 'rm -rf %s' % uploadfile
            utils._exec_pipe(rm_cmd)

        if not os.path.exists(DOWNLOAD_TAR_DIR):
            os.makedirs(DOWNLOAD_TAR_DIR)

        with open(uploadfile, 'w') as fout:                  # creates the file where the uploaded file should be stored
            fout.write(webfiles.file.read())

        get_host_ip = db_api.host_get_all()
        for host in get_host_ip:
            with open(LICH_HOST_IP_FILE, 'w') as f:
                f.write(host.ip)
                f.write('\n')

        os.popen("rm -rf %s" % (DECOMMPRESS_DIR))
        if not os.path.exists(DECOMMPRESS_DIR):
            os.makedirs(DECOMMPRESS_DIR)

        decompression_file_cmd = 'tar -xf %s -C %s/' %(uploadfile, DECOMMPRESS_DIR)
        utils._exec_pipe(decompression_file_cmd)
        files = os.listdir(DECOMMPRESS_DIR)
        bak_files = files
        ump_files = []
        for f in files:
            judge_cmd = '%s/%s -c %s/%s' %(UMP_LICENSE_CMD_DIR, 'license_dispatch', DECOMMPRESS_DIR, f)
            ret, stdout, stderr = utils._exec_pipe(judge_cmd)
            if ret == 0:
                sou_f = '%s/%s' %(DECOMMPRESS_DIR, f)
                dst_f = '%s/%s-%s' %(DECOMMPRESS_DIR, f, self.strtime)
                change_name = 'mv %s %s' %(sou_f, dst_f)
                utils._exec_pipe(change_name)
                ump_files.append(dst_f)

        lich_file = [x for x in files if x not in ump_files]
        for umpfile in ump_files:
            cp_file = 'cp %s %s' %(umpfile, UMP_LICENSE_DIR)
            utils._exec_pipe(cp_file)

        decompression_file_cmd = 'tar -xf %s -C %s/' % (uploadfile, DECOMMPRESS_DIR)
        utils._exec_pipe(decompression_file_cmd)

        kwargs = {'node_license':{}}
        for lf in lich_file:
            f = '%s/%s' % (DECOMMPRESS_DIR, lf)
            with open(f, 'r') as fread:
                kwargs['node_license'][f] = fread.read()

        web.header("Content-Type", "application/json")
        body = {"LicenseActivity": {'params': kwargs}}

        return utils.web_return(body)


